<?php
namespace MLM\Controller;

use Zend\View\Model\ViewModel;
use Zend\Authentication\Result;
use Zend\Authentication\AuthenticationService;

class AgentController extends \MLM\Model\Generic\Controller {

     public function indexAction() {
            $identity = $this->hasSession();
            $this->layout('layout/member');
            $view = new ViewModel();
            //Get Messages Notif
            $this->getMsgNotif($identity->member_type_id, $identity->member_id);
            return $view;
     }

     public function buysnAction() {
            $identity = $this->hasSession();
            $this->layout('layout/member');
            $view = new ViewModel();

            $script = $this->getServiceLocator()->get('viewhelpermanager')
                            ->get('inlineScript');
                    $script->appendScript("
                       jQuery(function($) {

                    $('[data-rel=tooltip]').tooltip();

                    $('.select').css('width','150px').select2({allowClear:true})
                    .on('change', function(){
                            $(this).closest('form').validate().element($(this));
                    });


                    var validation = false;
                    $('#fuelux-wizard').ace_wizard().on('change' , function(e, info){
                            if(info.step == 1 && validation) {
                                    if(!$('#validation-form').valid()) return false;
                            }
                            if(info.step == 2) {
                                return konfirmasiPembelian();
                            }
                    }).on('finished', function(e) {
                            $('#inputForm').submit();
                            /*
                            bootbox.dialog('Thank you! Your information was successfully saved!', [{
                                    'label' : 'OK',
                                    'class' : 'btn-small btn-primary',
                                    }]
                            );
                            */
                    }).on('stepclick', function(e, info){

                            //return false;//prevent clicking on steps

                    });


                    //documentation : http://docs.jquery.com/Plugins/Validation/validate


             });

            $('#qty').ace_spinner({value:10,min:1,max:9999999,step:10, btn_up_class:'btn-info' , btn_down_class:'btn-info'})
                .on('change', function(){
                        //alert(this.value)
                        setTotalHarga(this.value);
                });
                    ");

            $request = $this->getRequest();

            $db = $this->_db;
            $conn = $db->getDriver()->getConnection();

            if ($request->isPost()) {
                $conn->beginTransaction();
                $post = $request->getPost();

                $qty   = $post['qty'];
                $price = $post['price'];
                $totalPrice = $post['totalPrice'];
                $caraBayar   = $post['rdPembayaran'];

                /////
                $transStorage = new \MLM\Model\Transaction\Storage($db);

                $memberId = $identity->member_id;
                $transTypeCode = "T003";

                //Get Trans Type ID
                $transType = $transStorage->getTransType($transTypeCode);
                while ($transType->next()) {
                    $res = $transType->current();
                    $transTypeId = $res["trans_type_id"];
                }

                //InsertTH
                $dataTH = array(
                    "trans_type_id" => $transTypeId,
                    "trans_code"    => $transTypeCode.'/'.date('Y/m/d-H.i.s'),
                    "member_id"     => $memberId,
                    "trans_status"    => "APPROVAL",
                    "trans_dtm"     => $transStorage->now()
                );

                $insertTH = $transStorage->insertDataTrans("trans_header", $dataTH);

                if(!$insertTH){

                    $conn->rollback();
                    $view->setVariable('errmsg', 'Pembelian Produk gagal, hubungi Admin');
                    return $view;

                }


                $contactStorage = new \MLM\Model\Member\Contact\Storage($db);
                $memberContact = $contactStorage->getMemberContact($memberId);
                while ($memberContact->next()) {
                    $res = $memberContact->current();
                    $msisdn = $res["contact_mobile"];
                }

                //InsertTD                
                $dataTD = array(
                    "trans_header_id" => $insertTH,
                    "account_num1"    => $identity->member_code,
                    "msisdn"          => $msisdn,
                    "amount1"         => $totalPrice,
                    "xs3"             => $caraBayar,
                    "xn1"             => $price,
                    "xn2"             => $qty,
                    "mutation_type"   => 'D'
                );

                $insertTD = $transStorage->insertDataTrans("trans_detail", $dataTD);

                if(!$insertTD){
                    $conn->rollback();
                    $view->setVariable('errmsg', 'Pembelian Produk gagal, hubungi Admin');
                    return $view;                   
                }
                
                $conn->commit();

                //Jika cash atau transfer
                $tmp = ($caraBayar == 1 || $caraBayar == 3) ? ", silahkan lakukan konfirmasi pembayaran setelah anda membayar" : "";

                return $this->redirect()->toUrl('buysn?msg=Pembelian SN Sukses'.$tmp);
                

            }


            
            $confStorage = new \MLM\Model\Sysconfig\Storage($db);
            $getSNPrice = $confStorage->getConfigByName('SN_PRICE');
            while ($getSNPrice->next()) {
                $res = $getSNPrice->current();
                $snPrice = $res["int_value"];
            }
            $view->setVariable('snPrice', $snPrice);

            $accStorage = new \MLM\Model\Member\Account\Storage($db);
            $accountsPT = $accStorage->getAccountBank(100);

            $getBalance = $accStorage->getTotalBalance($identity->member_code);
            while ($getBalance->next()) {
                $res = $getBalance->current();
                $balance = $res["amount"];
            }

            $getParams = $this->getRequest()->getQuery();
            $msg = (isset($getParams["msg"])) ? $getParams["msg"] : "";

            $view->setVariable('accountsPT', $accountsPT);
            $view->setVariable('balance', $balance);
            $view->setVariable('msg', $msg);

            //Get Messages Notif
            $this->getMsgNotif($identity->member_type_id, $identity->member_id);
            return $view;
     }

     public function buyproductAction() {
            $identity = $this->hasSession();
            $this->layout('layout/member');

            $view = new ViewModel();
            $script = $this->getServiceLocator()->get('viewhelpermanager')
                    ->get('inlineScript');
            $script->appendScript("
                jQuery(function($) {

                    $('[data-rel=tooltip]').tooltip();

                    $('.select').css('width','150px').select2({allowClear:true})
                    .on('change', function(){
                            $(this).closest('form').validate().element($(this));
                    });


                    var validation = false;
                    $('#fuelux-wizard').ace_wizard().on('change' , function(e, info){
                            /*if(info.step == 1 && validation) {
                                    if(!$('#validation-form').valid()) return false;
                            }*/

                            if(info.step == 1) {
                                return cekProduct();
                            }
                            else if(info.step == 2) {
                                return konfirmasiPembelian();
                            }
                    }).on('finished', function(e) {
                            finishWizard();
                            /*
                            bootbox.dialog('Thank you! Your information was successfully saved!', [{
                                    'label' : 'OK',
                                    'class' : 'btn-small btn-primary',
                                    }]
                            );
                            */
                    }).on('stepclick', function(e){

                            //return false;//prevent clicking on steps

                    });


                    //documentation : http://docs.jquery.com/Plugins/Validation/validate


                    $('.chosen-select').chosen();

                    $('#modal-form').on('shown.bs.modal', function() {
                        $(this).find('.chosen-container').each(function() {
                            $(this).find('a:first-child').css('width', '210px');
                            $(this).find('.chosen-drop').css('width', '210px');
                            $(this).find('.chosen-search input').css('width', '200px');
                        });
                    })


             });

             $('#qty').ace_spinner({value:0,min:1,max:9999999,step:10, btn_up_class:'btn-info' , btn_down_class:'btn-info'})
                .on('change', function(){
                    return cekStok(this.value);
                        //alert(this.value)
                });

            ");

            $request = $this->getRequest();
			$getParams = $request->getQuery();
			if(isset($getParams['type'])){
				$type = $getParams['type'];
			}
            $db = $this->_db;
            $conn = $db->getDriver()->getConnection();


            if ($request->isPost()) {
                $conn->beginTransaction();
                $post = $request->getPost();

                //echo "<pre>";
                //print_r($post);

                $dataPembelian = $post["dataPembelian"];
                $caraBayar = $post["rdPembayaran"];

                $dataJson = base64_decode($dataPembelian);
                //echo $dataJson;
                //echo "<br>";
                $dataArray = json_decode($dataJson, true);
                //print_r($dataArray);
                //die();
                
                $transStorage = new \MLM\Model\Transaction\Storage($db);
                $stockStorage = new \MLM\Model\Product\Stock\Storage($db);
		
                /*
                if($type == 2){
                        $memberId = $identity->member_id;
                }else if ($type == 3){
                        $memberId = $identity->member_reff_id;
                }
                 * 
                 */

                $memberId = $identity->member_id;
                $transTypeCode = "T004";

                //Get Trans Type ID
                $transType = $transStorage->getTransType($transTypeCode);
                while ($transType->next()) {
                    $res = $transType->current();
                    $transTypeId = $res["trans_type_id"];
                }
                
                //InsertTH
                $dataTH = array(
                    "trans_type_id" => $transTypeId,
                    "trans_code"    => $transTypeCode.'/'.date('Y/m/d-H.i.s'),
                    "member_id"     => $memberId,
                    "trans_dtm"     => $transStorage->now(),
                    "trans_status"  => 'APPROVAL'
                );
      
                $insertTH = $transStorage->insertDataTrans("trans_header", $dataTH);

                if(!$insertTH){

                    $conn->rollback();
                    $view->setVariable('errmsg', 'Pembelian Produk gagal, hubungi Admin');
                    return $view;
                    
                }


                $contactStorage = new \MLM\Model\Member\Contact\Storage($db);
                $memberContact = $contactStorage->getMemberContact($memberId);
                while ($memberContact->next()) {
                    $res = $memberContact->current();
                    $msisdn = $res["contact_mobile"];
                }
                
                //InsertTD
                for ($x = 0; $x < count($dataArray); $x++){
                    //echo ($x+1).". ".$dataArray[$x]["prodname"]."<br>";

                    $dataTD = array(
                        "trans_header_id" => $insertTH,
                        "account_num1"    => $identity->member_code,
                        "msisdn"          => $msisdn,
                        "amount1"         => ($dataArray[$x]["price"]*$dataArray[$x]["qty"]),
                        "xs1"             => $dataArray[$x]["suplierId"],
                        "xs2"             => $dataArray[$x]["prodname"],
                        "xs3"             => $caraBayar,
                        "xn1"             => $dataArray[$x]["prodid"],
                        "xn2"             => $dataArray[$x]["qty"],
                        "xn3"             => $dataArray[$x]["agentId"],
                        "mutation_type"   => 'D'
                    );

                    $insertTD = $transStorage->insertDataTrans("trans_detail", $dataTD);

                    if(!$insertTD){
                        $conn->rollback();
                        $view->setVariable('errmsg', 'Pembelian Produk gagal, hubungi Admin');
                        return $view;
                        break;
                    }

                    //Kurangi stok produk
                    $productId = $stockStorage->updateStock($dataArray[$x]["prodid"], $dataArray[$x]["agentId"], '-', $dataArray[$x]["qty"]);

                    if(!$productId){
                        $conn->rollback();
                        $view->setVariable('errmsg', 'Pembelian Produk gagal, hubungi Admin');
                        return $view;
                        break;
                    }

                }

                $conn->commit();

                //Jika cash atau transfer
                $tmp = ($caraBayar == 1 || $caraBayar == 3) ? ", silahkan lakukan konfirmasi pembayaran setelah anda membayar" : "";

                return $this->redirect()->toUrl('buyproduct?msg=Pembelian Produk Sukses'.$tmp);
                
            }


            $storage = new \MLM\Model\Agent\Storage($db);
            $configstorage = new \MLM\Model\Sysconfig\Storage($db);

            $supliers = $storage->getSuplierList();
            $agents = $storage->getAgentList($identity->member_reff_id);
            $getMinOrder = $configstorage->getConfigByName('MIN_ORDER_AGENT');
            while ($getMinOrder->next()) {
                $resMO = $getMinOrder->current();
                $minOrder = $resMO["int_value"];
            }

            $view->setVariable('supliers', $supliers);
            $view->setVariable('agents', $agents);
            $view->setVariable('isAgent', $identity->member_reff_id);
            $view->setVariable('minOrder', $minOrder);

            $accStorage = new \MLM\Model\Member\Account\Storage($db);
            $accountsPT = $accStorage->getAccountBank(100);

            $getBalance = $accStorage->getTotalBalance($identity->member_code);
            while ($getBalance->next()) {
                $res = $getBalance->current();
                $balance = $res["amount"];
            }
				
		 
            $getParams = $this->getRequest()->getQuery();
            $msg = (isset($getParams["msg"])) ? $getParams["msg"] : "";

            $view->setVariable('accountsPT', $accountsPT);
            $view->setVariable('balance', $balance);
            $view->setVariable('msg', $msg);

            //Get Messages Notif
            $this->getMsgNotif($identity->member_type_id, $identity->member_id);
            return $view;
     }


    public function confirmlistAction(){
        $identity = $this->hasSession();
        $this->layout('layout/member');
        $view = new ViewModel();

        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $identity->member_id);

        return $view;
    }

    public function payconfirmAction(){
        $identity = $this->hasSession();
        $this->layout('layout/member');
        $view = new ViewModel();

        $getParams = $this->getRequest()->getQuery();
        $transId = $getParams["transId"];
        $msg = (isset($getParams["msg"])) ? $getParams["msg"] : "";

        $db = $this->_db;
        $conn = $db->getDriver()->getConnection();

        $request = $this->getRequest();
        if ($request->isPost()) {
            $conn->beginTransaction();
            $post = $request->getPost();

            $transId = $post["transId"];
            $tglBayar = $post["tglBayar"];
            $caraBayar = $post["caraBayar"];
            $rekAsal = $post["rekAsal"];
            $rekTujuan = $post["rekTujuan"];
            $jmlTransfer = $post["jmlTransfer"];
            $ket = $post["ket"];

            $agentStorage = new \MLM\Model\Agent\Storage($db);

            /*
            $dataTrans = array(
                'trans_header_id' => $transId,
                'pay_method' => $caraBayar,
                'from_account_id' => $rekAsal,
                'to_account_id' => $rekTujuan,
                'transfer_amount' => $jmlTransfer,
                'notes' => $ket
            );
             *
             */

            $dataTrans = array(
                $transId,
                $tglBayar,
                $caraBayar,
                $rekAsal,
                $rekTujuan,
                $jmlTransfer,
                $ket
            );


            $paymentId = $agentStorage->savePaymentConfirm($dataTrans);

            if(!$paymentId){
                $conn->rollback();
                $view->setVariable('errmsg', 'Konfirmasi Pembayaran Gagal, hubungi Admin');
                return $view;
            }

            $data = array(
                'trans_status'  => 'PAY_CONFIRM'
            );
            $where = array('trans_header_id' => $transId);
            $res = $agentStorage->updateTransStatus($data, $where);

            $conn->commit();

            return $this->redirect()->toUrl('payconfirm?msg=Konfirmasi Pembayaran Sukses, menunggu verifikasi Admin');


            die();
        }

        $transStorage = new \MLM\Model\Transaction\Storage($db);
        $transDetail = $transStorage->getPriceTransDetail($transId);

        while ($transDetail->next()) {
            $res = $transDetail->current();
            $transCode = $res["trans_code"];
            $totalTrans = $res["amount1"];
        }

        $accStorage = new \MLM\Model\Member\Account\Storage($db);
        $getAccMember = $accStorage->getAccountBank($identity->member_id);
        $getAccPT = $accStorage->getAccountBank(100);

        $view->setVariable('transId', $transId);
        $view->setVariable('transCode', $transCode);
        $view->setVariable('totalTrans', $totalTrans);
        $view->setVariable('msg', $msg);
        $view->setVariable('getAccMember', $getAccMember);
        $view->setVariable('getAccPT', $getAccPT);

        $script = $this->getServiceLocator()->get('viewhelpermanager')
                ->get('inlineScript');
        $script->appendScript("
          jQuery(function($) {
            $('.chosen-select').chosen();

            $('#modal-form').on('shown.bs.modal', function() {
                $(this).find('.chosen-container').each(function() {
                    $(this).find('a:first-child').css('width', '210px');
                    $(this).find('.chosen-drop').css('width', '210px');
                    $(this).find('.chosen-search input').css('width', '200px');
                });
            })

            $('.date-picker').datepicker({autoclose:true}).next().on(ace.click_event, function(){
                            $(this).prev().focus();
                    });
        })
        ");

        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $identity->member_id);

        return $view;
    }


    public function stockAction() {
        $identity = $this->hasSession();

        $this->layout('layout/member');
        $view = new ViewModel();

        /*
        if ($identity->member_id == 100 || $identity->member_reff_id == "")
            $memberId = $identity->member_id;
        else $memberId = $identity->member_reff_id;
         * 
         */

        $memberId = $identity->member_id;

        $view->setVariable('memberId', $memberId);
        
        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $identity->member_id);

        return $view;
    }


    public function agentlistAction()
    {

        $identity = $this->hasSession();
        $this->layout('layout/admin');

        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $identity->member_id);

        $view = new ViewModel();

        $script = $this->getServiceLocator()->get('viewhelpermanager')
                ->get('inlineScript');
                $script->appendScript("
                  jQuery(function($) {
                    $('.chosen-select').chosen();

                    $('#modal-form').on('shown.bs.modal', function() {
                        $(this).find('.chosen-container').each(function() {
                            $(this).find('a:first-child').css('width', '210px');
                            $(this).find('.chosen-drop').css('width', '210px');
                            $(this).find('.chosen-search input').css('width', '200px');
                        });
                    });

                })
                ");

        $storage = new \MLM\Model\Product\Storage($this->_db);
        $supliers = $storage->listSuplier();
        $view->setVariable('supliers', $supliers);

        return $view;

    }


     //Get Messages Notif
    private function getMsgNotif($memberTypeId, $memberId){


        if ($memberId == 100) $memberId2 = $memberId;
        else{
            $identity = $this->hasSession();
            //$memberId2 = ($identity->member_reff_id == "") ? $memberId : $identity->member_reff_id;
            $memberId2 = $memberId;
            $isAgent = $identity->member_reff_id;
        }


        $notifStorage = new \MLM\Model\Notification\Storage($this->_db);
        $notifMsg = new \MLM\Model\Notification($notifStorage);
        $newMsgCnt = $notifMsg->getCountNewMsg($memberId);
        $newMsgList = $notifMsg->getNewMsgList($memberId);
        $newAlertCnt = $notifMsg->getCountAlertApproval($memberTypeId, $memberId2, $isAgent);
        $newAlertList = $notifMsg->getAlertApproval($memberTypeId, $memberId2, $isAgent);

        $action = $this->getEvent()->getRouteMatch()->getParam('action');
        $control = $this->getEvent()->getRouteMatch()->getParam('controller');

        $this->layout()->menu = $control.'\\'.$action;
        $this->layout()->newMsgCnt = $newMsgCnt;
        $this->layout()->newMsgList = $newMsgList;
        $this->layout()->newAlertCnt = $newAlertCnt;
        $this->layout()->newAlertList = $newAlertList;

    }

     private function hasSession() {
            $auth = new AuthenticationService();

            $identity = $auth->getIdentity();
            //print_r($identity);
            if (!$auth->hasIdentity()) {
                    //echo "gak ada session";
                    return $this->redirect()->toRoute('application/default', array('controller' => 'Index', 'action' => 'login'));
            } else {
                    return $auth->getIdentity();
            }
    }

}
?>
